//
//  RHAddPlant2VC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/2.
//

#import "RHAddMePlantVC.h"
#import "RHAddCommonModel.h"
#import "RHAddMePlantCell.h"
#import "LocationManager.h"
#import "WSDatePickerView.h"
#import "RHChoiceMePlantTypeView.h"
#import "RHMeSystemModel.h"
#import "RHChoiceMultipleSystemVC.h"
#import "RHMeOptionTypeModel.h"
#import "RHMultipeImagePickView.h"
#import "RHChoiceCityView.h"
#import "ChoicePlantTypeView.h"
#import "RHDeviceModel.h"
#import "RHUserModel.h"
#import "RHSelectUserVC.h"
#import "RHChoiceTimeZoneView.h"

@interface RHAddMePlantVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) RHMultipeImagePickView *pictureView;

@property (nonatomic, strong) UIView *footerView;

@property (nonatomic ,assign) NSInteger compressIndex;//压缩图片序号

@property (nonatomic ,strong) NSMutableArray *imgUrlArr;//已经上传的图片url

@property (nonatomic ,strong) NSDictionary *addressParaDic;

@property (nonatomic ,strong) RHPlantTypeModel *curDeviceTypeModel;//当前选择的设备类型

@property (nonatomic ,strong) RHUserModel *user;//所属用户
@end

@implementation RHAddMePlantVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"创建电站".rh_localized;
    [self createData];
    [self setupUI];
}

- (void)setupUI{
   
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 15)];
    _tableView.tableFooterView = self.footerView;
    [_tableView registerClass:[RHAddMePlantCell class] forCellReuseIdentifier:AddPlantCell_Normal];
    [_tableView registerClass:[RHAddMePlantCell class] forCellReuseIdentifier:AddPlantCell_Select];
    [_tableView registerClass:[RHAddMePlantCell class] forCellReuseIdentifier:AddPlantCell_Location];
    [self.view addSubview:_tableView];
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    //获取当前位置
    [self locationAction];
    [self getCurrentZone];
}
-(void)locationAction
{
    kWeakSelf;
    [[LocationManager manager] setGeocodeLocationComp:^(CLPlacemark *place) {
        NSString *address = [NSString stringWithFormat:@"%@--%@--%@--%@--%@",SafeStr(place.country),SafeStr(place.administrativeArea),SafeStr(place.locality),SafeStr(place.subLocality),SafeStr([place.areasOfInterest firstObject])];
        for (RHAddCommonModel *model in weakSelf.dataArr) {
//            if ([model.tag isEqualToString:@"plant_city"]) {
//                model.content = [NSString stringWithFormat:@"%@%@%@",SafeStr(place.country),SafeStr(place.administrativeArea),SafeStr(place.locality)];;;
//            }
            if ([model.tag isEqualToString:@"plant_address"]) {
                model.content = [NSString stringWithFormat:@"%@%@",SafeStr(place.subLocality),SafeStr([place.areasOfInterest firstObject])];
            }
            if ([model.tag isEqualToString:@"plant_longitude"]) {
                model.content = [NSDecimalNumber decimalStringWithDouble:place.location.coordinate.longitude];
            }
            if ([model.tag isEqualToString:@"plant_latitude"]) {
                model.content = [NSDecimalNumber decimalStringWithDouble:place.location.coordinate.latitude];
            }
        }
        [weakSelf.tableView reloadData];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[LocationManager manager] startSerialLocation];
    });
}

-(void)getCurrentZone
{
    //获取当前时区
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    dateFormatter.dateFormat = @"Z";//只打印时区
    NSString *curDateString = [dateFormatter stringFromDate:[NSDate date]];
    curDateString = [curDateString stringByReplacingOccurrencesOfString:@"0" withString:@""];
    NSString *zone = [NSString stringWithFormat:@"UTC%@",curDateString];
    
    [self.dataArr enumerateObjectsUsingBlock:^(RHAddCommonModel*  _Nonnull plantModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([plantModel.tag isEqualToString:@"plant_zone"]) {
            plantModel.content = zone;
            *stop = YES;
        }
    }];
    [self.tableView reloadData];
}




#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 0)];
    
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return nil;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHAddCommonModel *model = self.dataArr[indexPath.row];
    if (indexPath.row == self.dataArr.count - 1) {
        model.isLast = YES;
    }
    kWeakSelf;
    RHAddMePlantCell *cell;
    if ([model.tag isEqualToString:@"plant_city"]) {
        cell = [tableView dequeueReusableCellWithIdentifier:AddPlantCell_Location];
        cell.locationBlock = ^{//定位
//            [QMUITips showLoadingInView:kAppWindow];
//            [weakSelf locationAction];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [QMUITips hideAllTipsInView:kAppWindow];
//            });
        };
    }else if (model.isSelection){
        cell = [tableView dequeueReusableCellWithIdentifier:AddPlantCell_Select];
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:AddPlantCell_Normal];
    }
    [cell setModel:model];
    
    cell.clickBlock = ^{
        if ([model.tag isEqualToString:@"plant_date"]) {//选择日期
            [weakSelf selectDate:model];
        }
        if ([model.tag isEqualToString:@"plant_type"]) {//选择电站类型
            [weakSelf selectPlantType:model];
        }
        if ([model.tag isEqualToString:@"device_type"]) {//选择设备类型
            [weakSelf selectDeviceType:model];
        }
        if ([model.tag isEqualToString:@"plant_state"]) {//选择运营状态
            [weakSelf selectPlantRunStatus:model];
        }
        if ([model.tag isEqualToString:@"plant_system"]) {//选择系统
            [weakSelf getSystemList:model];
        }
        if ([model.tag isEqualToString:@"plant_city"]) {//选择城市
            [weakSelf selectCity:model];
        }
        if ([model.tag isEqualToString:@"plant_device"]) {//选择设备
            [weakSelf getDeviceList:model];
        }
        if ([model.tag isEqualToString:@"plant_user"]) {//选择设备
            [weakSelf getUserList:model];
        }
        if ([model.tag isEqualToString:@"plant_zone"]) {//选择时区
            [weakSelf showTimeZoneList:model];
        }
    };
    return cell;
}

- (UIView *)footerView{
 
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,300)];
        [_footerView setBackgroundColor:UIColor.clearColor];
            
        UIView *bgView =  [[UIView alloc] initWithFrame:CGRectMake(15, 15, SCREEN_WIDTH-30,200)];
        [bgView setBackgroundColor:UIColor.whiteColor];
        bgView.layer.cornerRadius = 8;
        bgView.qmui_borderColor = kBorderColor;
        bgView.qmui_borderWidth = 1;
        bgView.qmui_borderPosition = QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionBottom|QMUIViewBorderPositionTop;
        bgView.layer.qmui_maskedCorners = QMUILayerAllCorner;
        [_footerView addSubview:bgView];
            
            
        QMUILabel *lab = [QMUILabel labelWithFont:kSYSTEMFONT(14) textColor:kCOLOR_HEX(@"3F4443")textAligment:NSTextAlignmentLeft];
        [lab setText:@"电站图片".rh_localized];
        [bgView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.mas_offset(15);
            make.right.mas_offset(-15);
        }];
            
        QMUILabel *tipLab = [QMUILabel labelWithFont:kSYSTEMFONT(10) textColor:kCOLOR_HEX(@"#8B8D92") textAligment:NSTextAlignmentLeft];
        tipLab.numberOfLines = 0;
        [tipLab setText:@"（最多可上传3张图片，格式为jpeg ,png，文件大小不超过10m）".rh_localized];
        [bgView addSubview:tipLab];
        [tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.equalTo(lab.mas_bottom).offset(10);
            make.right.mas_offset(-15);
        }];
            
        _pictureView = [[RHMultipeImagePickView alloc]initWithController:self];
        _pictureView.isEditing = YES;
        
        [bgView addSubview:_pictureView];
        [_pictureView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_offset(0);
            make.top.equalTo(tipLab.mas_bottom).offset(10);
        }];
        kWeakSelf;
       
       
        QMUIButton *createBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [createBtn setTitle:@"创建".rh_localized forState:UIControlStateNormal];
        [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [createBtn.layer setCornerRadius:8];
        [createBtn setBackgroundColor:CMainColorGreen];
        [_footerView addSubview:createBtn];
        [createBtn addTarget:self action:@selector(checkInfo) forControlEvents:UIControlEventTouchUpInside];
        [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.bottom.mas_offset(-15);
            make.height.offset(50);
        }];

    }
    return _footerView;
}

-(void)selectDate:(RHAddCommonModel*)model
{
    kWeakSelf;
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
        NSTimeInterval interval = [selectDate timeIntervalSince1970];
        model.content = [NSString stringWithFormat:@"%ld",(NSInteger)interval*1000];
        [weakSelf.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    datePickerV.maxLimitDate = [NSDate date];
    datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-10 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    
    [datePickerV show];
}

#pragma mark ------ 选择电站类型
-(void)selectPlantType:(RHAddCommonModel*)model
{
    kWeakSelf;
    RHChoiceMePlantTypeView *typeView = [[RHChoiceMePlantTypeView alloc]init];
    typeView.titleLab.text = @"请选择电站类型".rh_localized;
    typeView.typeList = model.optionList;
    for (RHMeOptionTypeModel *typeModel in model.optionList) {
        if (typeModel.typeId == [model.content integerValue]) {
            typeView.curType = typeModel;
        }
    }
    typeView.choiceResultBlock = ^(RHMeOptionTypeModel * _Nonnull type) {
        if (type) {
            model.content = [NSString stringWithFormat:@"%ld",type.typeId];;
            [weakSelf.tableView reloadData];
        }
        
    };
    [typeView showAnimation];
}

#pragma mark ------ 选择设备类型
-(void)selectDeviceType:(RHAddCommonModel*)plantModel
{
    kWeakSelf;
    [QMUITips showLoadingInView:self.view];
    [RHPlantTypeModel startGetWithCompletionAPIKey:H_plantTypeAndProductTypeRelation argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
    
            NSArray *plnatTypeArr = resultModel.data;
            
            ChoicePlantTypeView *choiceView = [[ChoicePlantTypeView alloc] init];
            choiceView.titleLab.text = @"请选择设备类型".rh_localized;
            choiceView.plantTypeList = plnatTypeArr;
            choiceView.curType = plantModel.content;
            [choiceView scorllToCurrentValue];
            [choiceView showAnimation];
        
            choiceView.choiceResultBlock = ^(RHPlantTypeModel * _Nonnull typeModel) {
                if (typeModel == nil) {
                    return;
                }
                plantModel.content = typeModel.plantType;
                weakSelf.curDeviceTypeModel = typeModel;
                [weakSelf.tableView reloadData];
            };
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


#pragma mark ----- 选择城市
-(void)selectCity:(RHAddCommonModel*)model
{
    kWeakSelf;
    RHChoiceCityView *cityView = [[RHChoiceCityView alloc]init];
    cityView.choiceResultBlock = ^(NSString * _Nonnull address,NSDictionary *paraDic) {
        model.content = address;
        weakSelf.addressParaDic = paraDic;
        [weakSelf.tableView reloadData];
    };
    [cityView showAnimation];
}

#pragma mark ----- 选择投运状态
-(void)selectPlantRunStatus:(RHAddCommonModel*)model
{
    kWeakSelf;
    
    RHChoiceMePlantTypeView *typeView = [[RHChoiceMePlantTypeView alloc]init];
    typeView.typeList = model.optionList;
    for (RHMeOptionTypeModel *typeModel in model.optionList) {
        if (typeModel.typeId == [model.content integerValue]) {
            typeView.curType = typeModel;
        }
    }
    typeView.choiceResultBlock = ^(RHMeOptionTypeModel * _Nonnull type) {
        if (type) {
            model.content = [NSString stringWithFormat:@"%ld",type.typeId];;
            [weakSelf.tableView reloadData];
        }
        
    };
    [typeView showAnimation];
}

#pragma mark ----- 可添加的系统
-(void)getSystemList:(RHAddCommonModel*)model
{
    RHAddCommonModel *deviceTypeModel;
    for (RHAddCommonModel *model in self.dataArr) {
        if ([model.tag isEqualToString:@"device_type"]) {
            deviceTypeModel = model;
        }
    }
    if (deviceTypeModel.content.length == 0) {
        [QMUITips showInfo:deviceTypeModel.placeHolder];
        return;
    }
    [QMUITips showLoadingInView:self.view];

    [RHMeSystemModel startGetWithCompletionAPIKey:H_getPlantSystemListByDeviceType argument:@{@"systemType":self.curDeviceTypeModel.plantType} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            [self showSystemList:arr model:model];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           [self.tableView endHeaderRefresh];
           [self.tableView endFooterRefresh];
    }];

}

#pragma mark ----- 可添加的设备
-(void)getDeviceList:(RHAddCommonModel*)model
{
    __block RHAddCommonModel *deviceTypeModel;
    [self.dataArr enumerateObjectsUsingBlock:^(RHAddCommonModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.tag isEqualToString:@"device_type"]) {
            deviceTypeModel = obj;
        }
    }];
    if (deviceTypeModel.content.length == 0) {
        [QMUITips showInfo:deviceTypeModel.placeHolder];
        return;
    }
    [QMUITips showLoadingInView:self.view];

    [RHDeviceModel startGetWithCompletionAPIKey:H_getNoAddPlantDeviceListByDeviceType argument:@{@"systemType":ValidNullData(deviceTypeModel.content)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
           
            [self showDeviceList:arr model:model];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
    }];

}

#pragma mark ----- 管理层选择所属用户
-(void)getUserList:(RHAddCommonModel*)model
{
   
    kWeakSelf;
    RHSelectUserVC *userVC = [[RHSelectUserVC alloc]init];
    userVC.url = H_selectUserWhenAddingPlant;
    userVC.selectBlock = ^(RHUserModel * _Nonnull userModel) {
        model.content = userModel.userName;
        weakSelf.user = userModel;
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:userVC animated:YES];

       

}

-(void)showSystemList:(NSArray*)systemList  model:(RHAddCommonModel*)model
{
    RHChoiceMultipleSystemVC *vc = [[RHChoiceMultipleSystemVC alloc]initWithSystemList:systemList];
    vc.curSystems = model.systemList;
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    [vc showAnimation];
    kWeakSelf;
    vc.choiceResultBlock = ^(NSArray<RHMeSystemModel*> *arr) {
        model.systemList = arr;
        model.content = [NSString stringWithFormat:@"%ld%@",arr.count,@"个".rh_localized];
        [weakSelf.tableView reloadData];
    };
}

-(void)showDeviceList:(NSArray*)deviceList  model:(RHAddCommonModel*)model
{
    RHChoiceMultipleSystemVC *vc = [[RHChoiceMultipleSystemVC alloc]initWithDeviceList:deviceList];
    vc.curDevices = model.deviceList;
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    [vc showAnimation];
    kWeakSelf;
    vc.choiceResultBlock = ^(NSArray<RHDeviceModel*> *arr) {
        if (arr == nil) {
            return;
        }
        NSMutableArray *addArr = [NSMutableArray arrayWithArray:arr];
        model.deviceList = addArr;
        model.content = [NSString stringWithFormat:@"%ld%@",arr.count,@"个".rh_localized];
        [weakSelf.tableView reloadData];
    };
}


#pragma mark ------ 选择时区 -------
-(void)showTimeZoneList:(RHAddCommonModel*)plantModel;
{
    RHChoiceTimeZoneView *choiceView = [[RHChoiceTimeZoneView alloc] init];
    choiceView.titleLab.text = @"请选择电站时区".rh_localized;
    choiceView.curTimeZone = plantModel.content;
    [choiceView scorllToCurrentValue];
    [choiceView showAnimation];
    kWeakSelf;
    choiceView.choiceResultBlock = ^(NSString * _Nonnull zone) {
        if (zone == nil) {
            return;
        }
        plantModel.content = zone;
        [weakSelf.tableView reloadData];
    };
}


-(void)checkInfo
{
    [self.view endEditing:YES];
    self.compressIndex = 0;
    [self.imgUrlArr removeAllObjects];
    
    BOOL checkResult = YES;
    for (RHAddCommonModel *model in self.dataArr) {
        if ([model.tag isEqualToString:@"plant_name"]) {
            NSString *plantName = model.content;
            if(plantName.length == 0 || (plantName.length>0&&plantName.length<4)){
                [QMUITips showError:@"电站名称请输入4至32个字符".rh_localized];
                checkResult = NO;
                break;
            }
        }
       
        if ([model.tag isEqualToString:@"plant_address"]) {
            NSString *plantAdress = model.content;
            if(plantAdress.length == 0 || (plantAdress.length>0&& (plantAdress.length<2||plantAdress.length>64))){
                [QMUITips showError:@"电站地址请输入2至64个字符".rh_localized];
                checkResult = NO;
                return;
            }
        }
       
        if ([model.tag isEqualToString:@"plant_type"]) {
            NSString *plantType = model.content;
            if(plantType.length == 0){
                [QMUITips showError:model.placeHolder];
                checkResult = NO;
                break;
            }
        }
        if ([model.tag isEqualToString:@"plant_state"]) {
            if (model.content.length == 0) {
                [QMUITips showError:model.placeHolder];
                checkResult = NO;
                break;
            }
        }
        if ([model.tag isEqualToString:@"plant_city"]) {
            if (model.content.length == 0) {
                [QMUITips showError:model.placeHolder];
                checkResult = NO;
                break;
            }
        }
   
        if (model.content.length == 0&&model.isRequired) {
            [QMUITips showError:model.placeHolder];
            checkResult = NO;
            break;
        }
        
    }
    
    if (checkResult == NO) {
        return;
    }
    if(self.pictureView.needUploadImageArr.count == 0){
      //没有图片要上传就直接提交参数
        [self addPlant];
        return;
    }else{
        [self uploadHeadImage];
    }
    
}

#pragma mark -------- 图片上传 ----------------
-(void)uploadHeadImage
{

    kWeakSelf;
    [QMUITips showLoading:@"压缩图片...".rh_localized inView:self.view];
    UIImage *image = [self.pictureView.needUploadImageArr safeObjectAtIndex:self.compressIndex];
    //压缩到500K
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *compressImg = [self compressImageQuality:image toByte:2000];
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:weakSelf.view];
            
            //上传头像
            [QMUITips showLoading:@"上传图片...".rh_localized inView:self.view];
            [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"ios_image"} image:compressImg imageName:nil requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                if(resultModel.code == 200){
                    weakSelf.compressIndex ++;
                    //保存图片参数
                    NSString *url = request.responseObject[@"url"];
                    [weakSelf.imgUrlArr addObject:ValidNullData(url)];
                    //上传完了图片
                    if (weakSelf.compressIndex == weakSelf.pictureView.needUploadImageArr.count) {
                        [weakSelf addPlant];
                    }else{
                        [weakSelf uploadHeadImage];
                    }
                    
                    
                }
            } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
               
                
            }];
        });
    });

    
}

//压缩图片质量   maxLength  单位: kb
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}

#pragma mark ------ 提交参数
-(void)addPlant
{
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
  
    for (RHAddCommonModel *model in self.dataArr) {
        if (model.content.length>0) {
            [para setObject:model.content forKey:model.key];
        }
       
        if ([model.tag isEqualToString:@"plant_system"]) {//系统
            NSMutableArray *mtbArr = [NSMutableArray array];
            [model.systemList enumerateObjectsUsingBlock:^(RHMeSystemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [mtbArr addObject:@(obj.systemId)];
            }];
            if (mtbArr.count>0) {
                [para setObject:mtbArr forKey:model.key];
            }
        }
        if ([model.tag isEqualToString:@"plant_device"]) {//设备
            NSMutableArray *mtbArr = [NSMutableArray array];
            [model.deviceList enumerateObjectsUsingBlock:^(RHDeviceModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [mtbArr addObject:obj.deviceId];
            }];
            if (mtbArr.count>0) {
                [para setObject:mtbArr forKey:model.key];
            }
        }
        if ([model.tag isEqualToString:@"plant_user"]) {//所属用户
            [para setObject:@(self.user.userId) forKey:model.key];
        }
    }
    if (self.imgUrlArr.count>0) {
       
        NSString *urlStr = [self.imgUrlArr componentsJoinedByString:@","];
        [para setObject:urlStr forKey:@"imageUrl"];//图片
    }
    //地址id
    if (self.addressParaDic) {
        [para addEntriesFromDictionary:self.addressParaDic];
    }
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_plantAdd argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [kNotificationCenter postNotificationName:PlantListNeedUpdateNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


-(void)createData
{
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
    NSString *curDate = [NSString stringWithFormat:@"%ld",(NSInteger)interval*1000];
    
    NSArray *datas = @[
        @{@"title":@"电站名称".rh_localized,
          @"placeHolder":@"请输入电站名称".rh_localized,
          @"isRequired":@(1),
          @"tag":@"plant_name",
          @"isFirst":@(1),
          @"key":@"plantName"
        },
        @{@"title":@"电站类型".rh_localized,
          @"placeHolder":@"请选择电站类型".rh_localized,
          @"isSelection":@(1),
          @"optionList":@[
              @{
                  @"typeId":@(1),
                  @"typeName":@"电池储能电站"
              }
          ],
          @"isRequired":@(1),
          @"tag":@"plant_type",
          @"key":@"type"
        },
        @{@"title":@"设备类型".rh_localized,
          @"placeHolder":@"请选择设备类型".rh_localized,
          @"isSelection":@(1),
          @"isRequired":@(1),
          @"tag":@"device_type",
          @"key":@"plantType"
        },
        @{@"title":@"投运状态".rh_localized,
          @"placeHolder":@"请选择投运状态".rh_localized,
          @"isSelection":@(1),
          @"optionList":@[
              @{
                  @"typeId":@(0),
                  @"typeName":@"待运营"
              },
              @{
                  @"typeId":@(1),
                  @"typeName":@"运营"
              },
              @{
                  @"typeId":@(2),
                  @"typeName":@"停运"
              }
          ],
          @"isRequired":@(1),
          @"tag":@"plant_state",
          @"key":@"operationStatus"
        },
        @{@"title":@"城市".rh_localized,
          @"placeHolder":@"请选择城市".rh_localized,
          @"isSelection":@(1),
          @"isRequired":@(1),
          @"tag":@"plant_city",
          @"key":@"city"
        },
        @{@"title":@"地址".rh_localized,
          @"placeHolder":@"请输入详细地址".rh_localized,
          @"isRequired":@(1),
          @"tag":@"plant_address",
          @"key":@"address"
        },
        @{@"title":@"投建日期".rh_localized,
          @"placeHolder":@"请选择日期".rh_localized,
          @"isSelection":@(1),
          @"isRequired":@(1),
          @"tag":@"plant_date",
          @"key":@"constructionTime",
          @"content":curDate
        },
        @{@"title":@"电站时区".rh_localized,
          @"placeHolder":@"请电站时区".rh_localized,
          @"isSelection":@(1),
          @"isRequired":@(1),
          @"tag":@"plant_zone",
          @"key":@"timezone"
        },
        @{@"title":@"联系人".rh_localized,
          @"placeHolder":@"请输入联系人姓名".rh_localized,
          @"tag":@"plant_contact_name",
          @"key":@"maintenance"
        },
        @{@"title":@"联系电话".rh_localized,
          @"placeHolder":@"请输入联系人电话".rh_localized,
          @"tag":@"plant_contact_phone",
          @"key":@"phoneNumber"
        }
    ];
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:datas];
    
    //用户层或者户储类型  没有系统
    if ([PrivateMange share].currentUser.operationType == OperationTypeHouse) {
        [arrM addObject:@{@"title":@"下级设备".rh_localized,
                                 @"placeHolder":@"请选择设备".rh_localized,
                                 @"isSelection":@(1),
                                 @"canEdit":@(1),
                                 @"isRequired":@(1),
                                 @"tag":@"plant_device",
                                 @"isLast":@(1),
                                 @"key":@"deviceList"
                        }];
        
        datas = arrM.copy;
    }
    //工商储,大储
    if ([PrivateMange share].currentUser.operationType == OperationTypeIndustry||
        [PrivateMange share].currentUser.operationType == OperationTypeLargeIndustry) {
        [arrM addObject:@{@"title":@"添加系统".rh_localized,
                          @"placeHolder":@"请选择系统".rh_localized,
                          @"isSelection":@(1),
                          @"isRequired":@(1),
                          @"tag":@"plant_system",
                          @"isLast":@(1),
                          @"key":@"systemIds"
                        }
         ];
        
        datas = arrM.copy;
    }
    
    //用户以上层级(管理层)
    if ([PrivateMange share].currentUser.orgType != OrganizationTypeUser) {
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:datas];
        NSDictionary *user = @{@"title":@"所属用户".rh_localized,
                               @"placeHolder":@"请选择用户".rh_localized,
                               @"isSelection":@(1),
                               @"canEdit":@(1),
                               @"isRequired":@(1),
                               @"tag":@"plant_user",
                               @"key":@"userId"
        };
        [arrM insertObject:user atIndex:7];
        datas = arrM.copy;
    }
    
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHAddCommonModel class] json:datas];
    

}

-(NSMutableArray *)imgUrlArr
{
    if (!_imgUrlArr) {
        _imgUrlArr = [NSMutableArray array];
    }
    return _imgUrlArr;
}
@end
